<?php

	Abstract Class Yomm_Module_Devmod Extends Yomm_Controller
	{
		public $grid_config = array();
		
		public $devmod = null;
		
		public $check_sum = null;
		
		Public Function __construct()
		{
			parent::__construct();
			
			// LOAD CONFIG DEEPENDING ON THE CHECKSUM WHICH IS GIVEN!
			if(!isset($this->get->check_sum) || empty($this->get->check_sum))
			{
				throw new Yomm_Error('$this->get->check_sum is empty or not set in GridModule Class'); exit;
			}
			
			if(!array_key_exists($this->get->check_sum, $_SESSION))
			{
				throw new Yomm_Error('The devmod session config check_sum "'. $this->get->check_sum.'" is not valid/does not exists in current session. header dump' . print_r($_SERVER, true)); exit;
			} else {
				//new Error('devmod session config check_sum OK. header dump ' . print_r($_SERVER, true));
			}
			
			$this->check_sum = $this->get->check_sum;
			
			$grid_config = $this->session->{$this->check_sum}['grid_config'];
			
			/*
			 * not finished fix i guess
			 * if method is NOT frontend_add or frontend_edit the theme must be: $this->view->setTheme(Yomm_Config::BackendTheme);
			 */
			if($this->get->method == "add_ajax" || $this->get->method == "edit_ajax")
			{
				$grid_config['theme'] = Yomm_Config::VAR_BACKEND_THEME;
			}
			
			$this->grid_config = $grid_config;
			
			$methods_obj =  $this->session->{$this->check_sum}['grid_methods'];
			
			$this->devmod = new Yomm_Devmod();
			
			$this->devmod->import_config($grid_config, $methods_obj);
			
			$this->theme = $grid_config['theme'];
		}
		
		/**
		 * problem: have the same sql statement after a search. pushing reset button should end in displaying the original SQL statement.
		 */
		public function list_ajax()
		{
			$sql = (isset($this->grid_config['list']['sql'])) ? $this->grid_config['list']['sql'] : false;
			return $this->ajaxResponse($this->devmod->type('list')->sql($sql)->export(), false);
		}
		
		public function list_ajax_export()
		{
			$data = $this->db->select($this->grid_config['sql_table'], Yomm_Library_Convert::objectToArray($this->post), false, true);
			
			$export = new Yomm_Library_Export();
			$export->importObject($data);
			$content = base64_encode($export->exportCSV());
				
			$_SESSION['header_name'] = "{$this->grid_config['sql_table']}.csv";
			$_SESSION['header_content'] = $content;

			return SiteConfig::Domain . "?controller=admin&method=download&hash=" . md5(strlen($content));
			
		}
		
		public function list_ajax_search()
		{
			$sql_fields = array();
			foreach($this->grid_config as $types)
			{
				if(is_array($types))
				{
					if(array_key_exists('original', $types))
					{
						foreach($types['original'] as $k => $f)
						{
							$sql_fields[] = " $f LIKE '%{$this->get->search_str}%' ";
						}
					}
				}
			}
			
			$sql_fields = array_unique($sql_fields);
			
			$this->devmod->view->assign('search_str', $this->get->search_str);
			
			return $this->ajaxResponse($this->devmod->type('list')->sql('WHERE ' . implode(" OR ", $sql_fields))->export(), false);
		}
		
		public function edit_ajax()
		{
			return $this->ajaxResponse($this->devmod->type('edit')->where($this->post->id_param)->export(), false);
		}
		
		public function edit_ajax_save()
		{
			$handler = $this->devmod->type('edit')->values($this->post)->save();
			
			if($handler === true)
			{
				return $this->ajaxResponse(array('status' => true, 'message' => 'Das ver&auml;ndern der Daten war erfolgreich!'));
			} else {
				return $this->ajaxResponse(array('status' => false, 'message' => 'fehler beim update des inhaltes'));
			}
		}
		
		public function delete_ajax()
		{
			$deletion = $this->devmod->type('del')->where($this->post->id_param)->save();	
			
			if($deletion === true)
			{
				return $this->ajaxResponse(array('status' => true, 'message' => 'Der Eintrag wurde erfolgreich entfernt!'));
			} else {
				return $this->ajaxResponse(array('status' => false, 'message' => 'fehler beim entfernen des inhalts'));
			}
		}
		
		public function delete_ajax_multi()
		{
			if(count($this->post) == 0)
			{
				return $this->ajaxResponse(array('status' => false, 'message' => 'fehler beim entfernen des inhalts'));
			}
			
			if(!isset($this->post->multi_del) || count($this->post->multi_del) == 0)
			{
				return $this->ajaxResponse(array('status' => false, 'message' => 'Sie m&uuml;ssen mindistens ein Element ausw&auml;hlen.'));
			}	
			
			foreach($this->post->multi_del as $key => $id)
			{
				$deletion = $this->devmod->type('del')->where($id)->save();
				
				if($deletion === false)
				{
					return $this->ajaxResponse(array('status' => false, 'message' => 'fehler beim entfernen des inhalts'));
				}
			}
			
			return $this->ajaxResponse(array('status' => true, 'message' => 'Der Eintrag wurde erfolgreich entfernt!'));
		}
		
		public function add_ajax()
		{
			return $this->ajaxResponse($this->devmod->type('add')->export(), false);
		}
		
		public function add_ajax_save()
		{
			$handler = $this->devmod->type('add')->values($this->post)->save();
			
			if($handler !== false)
			{
				return $this->ajaxResponse(array('status' => true, 'message' => 'Ihr Eintrag wurde erfolgreich gespeichert.'));
			} else {
				return $this->ajaxResponse(array('status' => false, 'message' => 'Ihr Eintrag konnte nicht gespeichert werden. Pr&uuml;fen Sie alle zwingenden Felder.'));
			}
		}
		
		public function frontend_add_ajax_save()
		{
			$handler = $this->devmod->type('frontend_add')->values($this->post)->save();
			
			if($handler !== false)
			{
				return $this->ajaxResponse(array('status' => true, 'message' => '<div class="true" id="devmod_add_status">Ihr Eintrag wurde erfolgreich gespeichert.</div>'));
			} else {
				return $this->ajaxResponse(array('status' => false, 'message' => '<div class="false" id="devmod_add_status">Ihr Eintrag konnte nicht gespeichert werden. Pr&uuml;fen Sie alle zwingenden Felder.</div>'));
			}
		}
		
		Public Function image_upp()
		{
			if(isset($this->post->image_submit))
			{
				$image = new Yomm_Library_Image();
				
				$file = $image->Upload($_FILES['image_file']);
				
				if($file == false)
				{
					return $this->ajaxResponse('<script language="javascript" type="text/javascript">window.top.window.dmApp.imageUploadEnd(false, \''.$image->error.'\', 0, 0, 0)</script>', false);
				} else {
					return $this->ajaxResponse('<script language="javascript" type="text/javascript">window.top.window.dmApp.imageUploadEnd(true, \'upload_success\', '.$file.', \''.Image::Show($file).'\', \''.$this->get->field.'\')</script>', false);
				}
			}	
		}
		
		public function file_upp()
		{
			if(isset($this->post->file_submit))
			{
				$file = new Yomm_Library_FileHandler();
				
				$new_file = $file->UploadFile($_FILES['file_file']);
				
				if(!$new_file)
				{
					return $this->ajaxResponse("<script language=\"javascript\" type=\"text/javascript\">window.top.window.dmApp.fileUploadEnd(false, '{$file->getError()}', 0, 0, 0)</script>", false);
				} else {
					return $this->ajaxResponse("<script language=\"javascript\" type=\"text/javascript\">window.top.window.dmApp.fileUploadEnd(true, 'success', '{$new_file}', '{$file->getName($new_file)}', '{$this->get->field}')</script>", false);
				}
			}
			
			/*
			if(isset($this->post->file_submit))
			{
				$file_info = pathinfo($_FILES['file_file']['name']);
				
				$handler = $this->db->handler("file_lib", array(
					"name" => $file_info['extension']
				));
				
				if(!move_uploaded_file($_FILES['file_file']['tmp_name'], Yomm_Config::FileSave . $handler . '.'. $file_info['extension'])) {
					return $this->ajaxResponse('<script language="javascript" type="text/javascript">window.top.window.dmApp.ImageFrmSendStop(false, \'Fehler beim Hochladen des Files.\', 0)</script>', false);
				} else{
					$image = SiteConfig::Domain . Yomm_Config::FileSave . $handler . '.'. $file_info['extension'];
					return $this->ajaxResponse('<script language="javascript" type="text/javascript">window.top.window.dmApp.ImageFrmSendStop(true, \'upload_success\', '.$handler.', \''.$image.'\', \''.$this->get->field.'\')</script>', false);
				}
			}
			*/
		}
		
		public function addon_sqlCheckbox()
		{
			$_cfg = $this->devmod->get_config();
			
			$sql = $this->db->select($_cfg['sql_table'], "*", "WHERE " . $_cfg['edit']['where'], false);
			
			$_tfg = $_cfg['edit']['addons'][$this->post->identifier];
			
			$_tfg['args']['param_value'] = $this->devmod->helper->eval_vars($_tfg['args']['param_value'], $sql);
			
			$_t = $this->db->DeleteSql($_tfg['args']['ref_table']['table'], "{$_tfg['args']['ref_table']['devmod_base_ref']}='{$_tfg['args']['param_value']}'");
			
			if(isset($this->post->values))
			{
				foreach($this->post->values as $k => $v)
				{
					$handler = $this->db->handler($_tfg['args']['ref_table']['table'], array(
						$_tfg['args']['ref_table']['devmod_base_ref'] => $_tfg['args']['param_value'],
						$_tfg['args']['ref_table']['data_table_ref'] => $v
					));
					
					if($handler === false)
					{
						$err = new Yomm_Error('addon_submit error in GridCallback: ' . $handler);
						echo $err->getMessage();
					}
				}
			}
			return true;
		}
		
		/**
		 * TODO: there is currently no way to say if an image had an error while uploading
		 * 
		 * $this->get->identifier
		 * $this->get->check_sum
		 * $this->get->param_value
		 */
		public function addon_multiUpload()
		{
			$_cfg = $this->devmod->get_config();
			
			$_args = $_cfg['edit']['addons'][$this->get->identifier]['args'];
			
			$image = new Image();
			
			$file = $image->Upload($_FILES["file"]);
			
			if($file === false)
			{
				throw new Yomm_Error('error while uploading image in addon_multiUpload: ' . $_FILES["file"]["name"]); return false;
			}
			
			$return = $this->db->handler($_args['image_table']['name'], array(
				$_args['image_table']['param_image_id'] => $file,
				$_args['image_table']['param_cat_id'] => $this->get->param_value
			));
			
			if(!$return)
			{
				throw new Yomm_Error('error in uploading image/file for addon_multiUpload, see environement variables for details.');
				return false;
			}
		}
		
	}